const router = require('koa-router')();
const utility = require('utility');
/**路由地址前缀 */
router.prefix('/api/Administrator');
/**
 * 登录
 * @api {POST}        /Administrator/login            登录
 * @apiName           /Administrator/login
 * @apiGroup          Administrator
 * @apiVersion 0.1.0
 * @apiParam          {String}            user        用户名
 * @apiParam          {String}            password    密码
 * @apiSuccessExample Success-Response:
 * {
    "code": 0,
    "msg": "登录成功",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpJ9"
   }
 }
 */
router.post('/login',async function (ctx) {
    let { db, request: { body: { user, password } } } = ctx;

    if (!user) {
        ctx.errors('用户名不能为空');
        return;
    }

    if (!password) {
        ctx.errors('密码不能为空');
        return;
    }

    let condition = {
        where: {
            username: user,
            password: utility.md5(password)
        },
        attributes: ['id','username','phone', 'avatar', 'role_id'],
        include: {
            as: 'role',
            attributes: ['id','role','remake'],
            required: true,
            model: db.Role
        }
    };

    let data = await db.User.findOne(condition);

    if (!data) {
        ctx.errors('用户名或密码错误');
        return;
    }

    const {role: { id }} = data;
    const localToken = ctx.createToken(data, id, '2', 'hours');
    ctx.body = {code: 0,msg: '登录成功',token: localToken};
    db.Log.create({user_id: data.id,event: '登录'});
});
/**
 * 获取用户信息
 * @api {GET}         /Administrator/getMenu                     获取用户信息
 * @apiName           /Administrator/getMenu
 * @apiGroup          Administrator
 * @apiVersion 0.1.0
 * @apiSuccessExample Success-Response:
 * {
    "code": 0,
    "msg": "",
    "avatar": "https://img.52z.com/upload/news/image/20171106/20171106094122_15964.jpg",
    "introduction": "欢迎！",
    "name": "超级管理员",
    "roles": [
        "admin"
    ],
    "menu": "[{\"path\":\"/user\",\"redirect\":\"/user/index\",\"name\":\"user\",}]"
  }
 */
router.get('/getMenu', async function (ctx) {
    let { db } = ctx;

    let condition = {
        attributes: ['username', 'avatar', 'role_id'],
        include: {
            as: 'role',
            attributes: ['id','role','remake','menu'],
            required: true,
            model: db.Role
        }
    };

    let data = await db.User.findOne(condition);

    ctx.body = { code: 0, msg: '', avatar: data.avatar, introduction: '欢迎！', name: '超级管理员', roles: [data.role.role], menu: data.role.menu};
});
/**
 * 退出
 * @api {GET}        /Administrator/logout         退出
 * @apiName          /Administrator/logout
 * @apiGroup         Administrator
 * @apiVersion 0.1.0
 * @apiSuccessExample Success-Response:
 * {
    "code": 0,
    "msg": "退出成功",
    "data": []
   }
 }
 */
router.get('/logout',function (ctx) {
    const { db, user: { User } } = ctx;

    ctx.success();

    db.Log.create({user_id: User.id,event: '退出登录'});

    return;
});
/**
 * 查询管理员操作日志
 * @api {GET}        /Administrator/getLog               查询管理员操作日志
 * @apiName          /Administrator/getLog
 * @apiGroup         Administrator
 * @apiVersion 0.1.0
 * @apiParam         {Number}            page=1          页数
 * @apiParam         {Number}            limit=10        每页多少
 * @apiParam         {String}            keywords        管理员名字或者id
 * @apiSuccessExample Success-Response:
 * {
    "code": 0,
    "msg": "success",
    "data": {
        "count": 88,
        "rows": [
            {
                "id": 1,
                "user_id": 1,
                "event": "登录",
                "createdAt": "2019-04-28T01:01:08.000Z",
                "updatedAt": "2019-04-28T01:01:08.000Z",
                "user": {
                    "username": "admin"
                }
            }
        ]
    }
  }
 */
router.get('/getLog',async function (ctx) {
    const { db, Op, query: { page = 1, limit = 10, keywords = '' } } = ctx;

    let condition = {
        limit: parseInt(limit, 10),
        offset: (parseInt(page, 1) - 1) * 10,
        include: {
            as: 'user',
            attributes: ['username'],
            required: true,
            model: db.User
        }
    };
    //如果关键字不为空
    if (keywords.trim()) {
        condition.where = {
            [Op.or]: [
            { user_id: { [Op.like]: '%' + keywords.trim() + '%' } },
            { id: { [Op.like]: '%' + keywords.trim() + '%' } },
            { '$user.username$': { [Op.like]: '%' + keywords.trim() + '%'} }
        ]
        };
    }
    //查询所有日志
    let data = await db.Log.findAndCountAll(condition);
    ctx.success(data);
});
module.exports = router;
